function resolveCourseConflicts(result) {
    let splitTag = "&";
    let allResultSet = new Set();
    result.forEach(singleCourse => {
        singleCourse.weeks.forEach(week => {
            singleCourse.sections.forEach(value => {
                let course = { sections: [], weeks: [] };
                course.name = singleCourse.name;
                course.teacher = singleCourse.teacher || "";
                course.position = singleCourse.position || "";
                course.day = singleCourse.day;
                course.weeks.push(week);
                course.sections.push(value);
                allResultSet.add(JSON.stringify(course));
            });
        });
    });
    let allResult = JSON.parse("[" + Array.from(allResultSet).join(",") + "]").sort((a, b) => {
        return a.day - b.day || a.sections[0] - b.sections[0];
    });

    // 合并冲突课程
    let contractResult = [];
    while (allResult.length > 0) {
        let firstCourse = allResult.shift();
        for (let i = 0; i < allResult.length && allResult[i].day === firstCourse.day;) {
            let current = allResult[i];
            if (firstCourse.weeks[0] === current.weeks[0] && firstCourse.sections[0] === current.sections[0]) {
                let names = firstCourse.name.split(splitTag);
                if (!names.includes(current.name)) {
                    firstCourse.name += splitTag + current.name;
                    firstCourse.teacher += splitTag + current.teacher;
                    firstCourse.position += splitTag + current.position;
                } else {
                    let index = names.indexOf(current.name);
                    let teachers = firstCourse.teacher.split(splitTag);
                    let positions = firstCourse.position.split(splitTag);
                    teachers[index] = [teachers[index], current.teacher].filter(x => x).join(",");
                    positions[index] = [positions[index], current.position].filter(x => x).join(",");
                    firstCourse.teacher = teachers.join(splitTag);
                    firstCourse.position = positions.join(splitTag);
                }
                allResult.splice(i, 1);
            } else {
                i++;
            }
        }
        contractResult.push(firstCourse);
    }

    // 合并连续节次
    let finallyResult = [];
    while (contractResult.length > 0) {
        let firstCourse = contractResult.shift();
        for (let i = 0; i < contractResult.length && contractResult[i].day === firstCourse.day;) {
            let current = contractResult[i];
            if (firstCourse.weeks[0] === current.weeks[0] &&
                firstCourse.name === current.name &&
                firstCourse.position === current.position &&
                firstCourse.teacher === current.teacher &&
                firstCourse.sections.slice(-1)[0] + 1 === current.sections[0]) {
                firstCourse.sections.push(...current.sections);
                contractResult.splice(i, 1);
            } else {
                i++;
            }
        }
        finallyResult.push(firstCourse);
    }

    // 合并周次
    contractResult = finallyResult;
    finallyResult = [];
    while (contractResult.length > 0) {
        let firstCourse = contractResult.shift();
        firstCourse.weeks.sort((a, b) => a - b);
        for (let i = 0; i < contractResult.length && contractResult[i].day === firstCourse.day;) {
            let current = contractResult[i];
            current.weeks.sort((a, b) => a - b);
            if (JSON.stringify(firstCourse.sections) === JSON.stringify(current.sections) &&
                firstCourse.name === current.name &&
                firstCourse.position === current.position &&
                firstCourse.teacher === current.teacher) {
                firstCourse.weeks = [...new Set([...firstCourse.weeks, ...current.weeks])].sort((a, b) => a - b);
                contractResult.splice(i, 1);
            } else {
                i++;
            }
        }
        finallyResult.push(firstCourse);
    }

    return finallyResult;
}

function scheduleHtmlParser(html) {
    const result = [];
    try {
        // 深度展平嵌套数组
        const courseInfo = JSON.parse(html)
            .flat(Infinity)
            .filter(x => x && typeof x === 'object');

        courseInfo.forEach(item => {
            try {
                // 处理可能的数组包装和异常数据
                const course = (Array.isArray(item) ? item[0] : item) || {};

                // 强化空值检查
                if (!course.courseName?.trim()) {
                    console.warn('课程名称缺失:', course);
                    return;
                }

                // 构建课程对象
                const re = {
                    name: course.courseName.trim(),
                    teacher: (course.teacherName || '未知教师').trim(),
                    position: (course.location || '未知地点').trim(),
                    day: 0,
                    sections: [],
                    weeks: []
                };

                // 解析星期（兼容非常规格式）
                const classTime = course.classTime?.toString() || "";
                const dayMatch = classTime.match(/(?:周|星期|周次)?(\d)/);
                if (!dayMatch || (re.day = parseInt(dayMatch[1])) < 1 || re.day > 7) {
                    console.warn('星期解析失败:', classTime);
                    return;
                }

                // 解析节次（兼容多格式）
                const sectionPart = classTime.replace(/[^\d]/g, '').slice(dayMatch[0].length);
                const sections = [];
                for (let i = 0; i < sectionPart.length; i += 2) {
                    const sec = parseInt(sectionPart.substr(i, 2));
                    if (sec > 0 && sec < 50) sections.push(sec);
                }
                if (sections.length === 0) {
                    console.warn('节次解析失败:', classTime);
                    return;
                }
                re.sections = [...new Set(sections)].sort((a,b) => a-b);

                // 解析周次（关键修复部分）
                const weekDetails = course.classWeekDetails?.toString().replace(/周/g, '') || "";
                const weeks = new Set();
                weekDetails.split(/[,，]/)
                    .map(x => x.trim())
                    .filter(x => x)
                    .forEach(part => {
                        const cleanPart = part.replace(/\s+/g, '');
                        if (/-/.test(cleanPart)) {
                            const [start, end] = cleanPart.split('-').map(Number);
                            if (!isNaN(start) && !isNaN(end)) {
                                for (let w = start; w <= Math.min(end, 30); w++) {
                                    if (w > 0) weeks.add(w);
                                }
                            }
                        } else {
                            const week = parseInt(cleanPart);
                            if (!isNaN(week)) {
                                if (week > 0 && week <= 30) weeks.add(week);
                            }
                        }
                    });

                re.weeks = Array.from(weeks).sort((a,b) => a-b);
                if (re.weeks.length === 0) {
                    console.warn('周次解析失败:', weekDetails);
                    return;
                }

                result.push(re);
            } catch (e) {
                console.error('单课程解析异常:', e);
            }
        });

        return resolveCourseConflicts(result);
    } catch (e) {
        console.error('全局解析失败:', e);
        return [];
    }
}